<template>
	<view class="page">
		<nav-bar fontColor="#FFF" bgColor="themeBgColor" type="transparentFixed" ></nav-bar>
        <!-- 公共组件-每个页面必须引入 -->
        <public-module></public-module>
		<canvas canvas-id="poster" class="poster"></canvas>
		<view class="mask"></view>
		<view class="goods_info_box">
			<image class="img" :src="dataInfo.goodsImg" mode="aspectFit"></image>
			<view class="goods_info">
				<image class="code" :src="dataInfo.recommendCodeGoods" mode="aspectFill"></image>
				<view class="info">
					<view class="name">{{dataInfo.goodsName}}</view>
					<view class="price">{{ dataInfo.goodsPrice }}</view>
				</view>
			</view>
			<view class="download">
				<!-- #ifndef H5 -->
				<button @click="onSaveImg">保存图片</button>
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<button class="download">长按保存图片</button>
				<!-- #endif -->
			</view>
		</view>
		<!-- #ifdef H5 -->
		<view class="poster_img">
			<image :src="posterImg" mode="aspectFill"></image>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	let settingWritePhotosAlbum = false;
	// 文字换行
	function drawtext(ctx, text, x, y, maxWidth) {
		let textArr = text.split("");
		let len = textArr.length;
		// 上个节点
		let previousNode = 1;
		// 记录节点宽度
		let nodeWidth = 0;
		// 文本换行数组
		let rowText = [];
		for (let i = 0; i < len; i++) {
			if (/[\u4e00-\u9fa5]/g.test(textArr[i])) {
				nodeWidth += 24;
			} else {
				nodeWidth += 12;
			}
			if (nodeWidth >= maxWidth) {
				rowText.push(text.substring(previousNode, i));
				previousNode = i;
				nodeWidth = 0;
			}
		}
		if(previousNode < text.length){
			rowText.push(text.substring(previousNode, text.length));
		}
		let rowLen = rowText.length;
		rowText.forEach((item, index) => {
			if (rowLen > 2 && index >= 1) {
				if (index == 1) {
					ctx.fillText(item + "...", x, y + (index + 1) * 33); //每行字体y坐标间隔20
				}
			} else {
				if (index == 0) {
					ctx.fillText(item, x, y + (index + 1) * 30);
				} else {
					ctx.fillText(item, x, y + (index + 1) * 33);
				}
			}
		});
	}
	export default {
		data() {
			return {
				posterImg: "",
				dataInfo: {
					headImgs: []
				}
			};
		},
		//第一次加载
		onLoad(e) {
			if (e.objId) {
				this.objId = e.objId;
				this.pageData();
			}
		},
		//页面显示
		onShow() {},
		//方法
		methods: {
			pageData() {
				this.$http
					.get('api/mall/goods/v1/info', {
						objId: this.objId
					})
					.then(res => {
						this.dataInfo = res.goodsRecommendShare;
						this.createPoster();
					});
			},
			onPageJump(url) {
				uni.navigateTo({
					url: url
				});
			},
			// 创建海报
			createPoster() {
				uni.showLoading({
					title: '加载中'
				});
				const ctx = uni.createCanvasContext('poster');
				ctx.fillRect(0, 0, 470, 640);
				ctx.setFillStyle("#FFF");
				ctx.fillRect(0, 0, 470, 640);
				uni.downloadFile({
					url: this.dataInfo.goodsImg,
					success: (res) => {
						if (res.statusCode === 200) {
							ctx.drawImage(res.tempFilePath, 0, 0, 470, 470);
							uni.downloadFile({
								url: this.dataInfo.recommendCodeGoods,
								success: (res) => {
									if (res.statusCode === 200) {
										ctx.drawImage(res.tempFilePath, 20, 490, 120, 120);
										ctx.setFontSize(24);
										ctx.setFillStyle('#333435');
										drawtext(ctx, this.dataInfo.goodsName, 160, 490, 278);
										ctx.setFillStyle('#ff4a4a');
										ctx.fillText(this.dataInfo.goodsPrice, 160, 600);
										ctx.draw(true, () => {
											// canvas画布转成图片并返回图片地址
											uni.canvasToTempFilePath({
												canvasId: 'poster',
												success: (res) => {
													uni.hideLoading();
													this.posterImg = res.tempFilePath;
												},
												fail: () => {
													uni.hideLoading();
													console.log('绘制失败');
												}
											})
										});
									}
								},
							});
						}
					},
				});
			},
			// 保存图片
			onSaveImg() {
				if (this.posterImg) {
					// #ifdef MP-WEIXIN
					if (settingWritePhotosAlbum) {
						uni.getSetting({
							success: res => {
								if (res.authSetting['scope.writePhotosAlbum']) {
									uni.downloadFile({
										url: this.posterImg,
										success: data => {
											if (data.statusCode == 200) {
												uni.saveImageToPhotosAlbum({
													filePath: data.tempFilePath,
													success: () => {
														uni.showToast({
															title: '保存成功'
														});
													}
												});
											}
										}
									});
								} else {
									uni.showModal({
										title: '提示',
										content: '请先在设置页面打开“保存相册”使用权限',
										confirmText: '去设置',
										cancelText: '算了',
										success: data => {
											if (data.confirm) {
												uni.openSetting();
											}
										}
									});
								}
							}
						});
					} else {
						settingWritePhotosAlbum = true;
						uni.authorize({
							scope: 'scope.writePhotosAlbum',
							success: () => {
								uni.downloadFile({
									url: this.posterImg,
									success: data => {
										if (data.statusCode == 200) {
											uni.saveImageToPhotosAlbum({
												filePath: data.tempFilePath,
												success: () => {
													uni.showToast({
														title: '保存成功'
													});
												}
											});
										}
									}
								});
							}
						});
					}
					// #endif
					// #ifdef H5
					uni.downloadFile({
						url: this.posterImg,
						success: data => {
							if (data.statusCode == 200) {
								window.open(data.tempFilePath);
							}
						}
					});
					// #endif
					// #ifdef APP-PLUS
					uni.saveImageToPhotosAlbum({
						filePath: this.posterImg,
						success: () => {
							uni.showToast({
								title: '保存成功'
							});
						}
					});
					// #endif
				} else {
					uni.showToast({
						title: '海报正在生成中，请稍后',
						icon: 'none'
					});
				}
			},
		},
		//页面隐藏
		onHide() {},
		//页面卸载
		onUnload() {},
		//页面下来刷新
		onPullDownRefresh() {},
		//页面上拉触底
		onReachBottom() {},
		//用户点击分享
		onShareAppMessage(e) {
			return this.wxShare();
		}
	};
</script>
<style lang="scss" scoped>
	@import '@/style/mixin.scss';

	.poster {
		width: 940rpx;
		height: 1280rpx;
		position: fixed;
		top: -10000rpx;
		left: 0rpx;
	}

	.page {
		position: relative;
		background-image: url("https://qn.kemean.cn/upload/202004/15/1586937083389kvcvg0qu.png");
		background-position: center center;
		background-repeat: no-repeat;
		background-size: cover;
		height: 100vh;
		width: 100%;

		.mask {
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.5);
		}

		.goods_info_box {
			margin-bottom: 80rpx;
			width: 470rpx;
			background-color: #FFFFFF;
			border-radius: 20rpx;
			overflow: hidden;
			position: absolute;
			bottom: 80rpx;
			left: 50%;
			transform: translateX(-50%);

			.img {
				width: 100%;
				height: 470rpx;
			}

			.goods_info {
				padding: 20rpx;
				display: flex;

				.code {
					width: 120rpx;
					height: 120rpx;
					margin-right: 20rpx;
					flex-shrink: 0;
				}

				.info {
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.name {
						font-size: 24rpx;
						color: #333435;
						@include bov();
					}

					.price {
						font-size: 24rpx;
						color: #ff4a4a;
					}
				}
			}

			.download {
				display: flex;
				justify-content: center;
				padding-bottom: 10rpx;

				button {
					font-size: 24rpx;
					color: #333;
					background-color: transparent;
					display: flex;
					align-items: center;

					&:before {
						content: "";
						@include bis("../../../static/icon/icon_download_black.png");
						width: 24rpx;
						height: 24rpx;
						margin-right: 15rpx;
					}
				}
			}
		}
	}
	.poster_img {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		image {
			width: 100%;
			height: 100%;
			opacity: 0;
		}
	}
</style>
